package com.xunyin.modules.shareorder.rest;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.xunyin.api.ApiResult;
import com.xunyin.api.XunyinException;
import com.xunyin.common.aop.NoRepeatSubmit;
import com.xunyin.common.bean.LocalUser;
import com.xunyin.common.interceptor.AuthCheck;
import com.xunyin.enums.AppFromEnum;
import com.xunyin.enums.BillDetailEnum;
import com.xunyin.enums.OrderStatusEnum;
import com.xunyin.event.TemplateBean;
import com.xunyin.event.TemplateEvent;
import com.xunyin.event.TemplateListenEnum;
import com.xunyin.modules.device.domain.TDevice;
import com.xunyin.modules.device.param.DeviceParam;
import com.xunyin.modules.device.service.TDeviceService;
import com.xunyin.modules.file.service.FileService;
import com.xunyin.modules.log.AppLog;
import com.xunyin.modules.log.service.mapper.TimelongRecordMapper;
import com.xunyin.modules.maincouponsend.service.mapper.TmainCouponUserMapper;
import com.xunyin.modules.membersuser.service.mapper.TMembersUserMapper;
import com.xunyin.modules.mp.service.WeixinPayService;
import com.xunyin.modules.mp.service.WeixinPayShareBusService;
import com.xunyin.modules.mtstore.domain.MtStoreRoom;
import com.xunyin.modules.mtstore.service.MtStoreRoomService;
import com.xunyin.modules.recharge.domain.TRechargeOrder;
import com.xunyin.modules.shareorder.bo.OrderDateHour;
import com.xunyin.modules.shareorder.domain.TShareOrder;
import com.xunyin.modules.shareorder.param.ExchangeRoomParam;
import com.xunyin.modules.shareorder.param.FinishOrderParam;
import com.xunyin.modules.shareorder.param.TShareOrderParam;
import com.xunyin.modules.shareorder.service.TShareOrderService;
import com.xunyin.modules.shareorder.service.mapper.TShareOrderMapper;
import com.xunyin.modules.shareorder.vo.TShareOrderForSwitchVo;
import com.xunyin.modules.shareorder.vo.TShareOrderVo;
import com.xunyin.modules.storeroom.param.TStoreRoomQueryParam;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.nettyV.client.PubMsg;
import com.xunyin.utils.DateUtils;
import com.xunyin.utils.DeviceUtil;
import com.xunyin.utils.DeviceUtil1;
import com.xunyin.utils.OrderNoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 包间订单控制器
 * </p>
 *
 * @author admin
 * @since 2022-9-26
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "包间订单模块", tags = "共享空间:包间订单模块")
public class ShareOrderController {

    private final TDeviceService tDeviceService;

    private final MtStoreRoomService mtStoreRoomService;

    private final TShareOrderService tShareOrderService;

    private final FileService fileService;

    private final WeixinPayShareBusService weixinPayShareBusService;

    private final TmainCouponUserMapper tmainCouponUserMapper;

    private final TShareOrderMapper tShareOrderMapper;

    private final WeixinPayService weixinPayService;

    private final TMembersUserMapper tMembersUserMapper;

    private final TimelongRecordMapper timelongRecordMapper;

    private final ApplicationEventPublisher publisher;

    /**
     * 根据订单id查看订单时间段内的使用情况
     */
    @AppLog(value = "根据订单id查看订单时间段内的使用情况", type = 1)
    //@AuthCheck
    @PostMapping("/getOrderInfo")
    @ApiOperation(value = "根据订单id查看订单时间段内的使用情况", notes = "根据订单id查看订单时间段内的使用情况")
    public JSONObject getOrderInfo(@RequestBody JSONObject jsonObject) {
        return tShareOrderService.getOrderInfo(jsonObject);
    }

    /**
     * 预约时间单内订单预约时间点已使用查询接口V2
     * 根据房间id查看订单时间段内的使用情况
     */
    @AppLog(value = "预约时间单内订单预约时间点已使用查询接口V2", type = 1)
    //@AuthCheck
    @PostMapping("/getTimeListOrderV2")
    @ApiOperation(value = "预约时间单内订单预约时间点已使用查询接口V2", notes = "预约时间单内订单预约时间点已使用查询接口V2")
    public ApiResult<List<OrderDateHour>> getTimeListOrderV2(@RequestBody TShareOrderParam tShareOrderParam) {
        List<OrderDateHour> data = tShareOrderService.getTimeListOrderV2(tShareOrderParam);
        return ApiResult.ok(data);
    }

    /**
     * 预约时间单内订单预约时间点已使用查询接口
     * 根据房间id查看订单时间段内的使用情况
     */
    @AppLog(value = "预约时间单内订单预约时间点已使用查询接口", type = 1)
    //@AuthCheck
    @PostMapping("/getTimeListOrder")
    @ApiOperation(value = "预约时间单内订单预约时间点已使用查询接口", notes = "预约时间单内订单预约时间点已使用查询接口")
    public ApiResult<Map<String, Object>> getTimeListOrder(@RequestBody TShareOrderParam tShareOrderParam) {
        Map<String, Object> data = tShareOrderService.getTimeListOrder(tShareOrderParam);
        return ApiResult.ok(data);
    }

    /**
     * 首页续单接口
     * 根据用户id获取当前正在使用的订单
     */
    @AppLog(value = "首页开门、续单接口", type = 1)
    @AuthCheck
    @PostMapping("/repeatOrder")
    @ApiOperation(value = "首页开门、续单接口", notes = "首页开门、续单接口")
    public ApiResult<List<TShareOrderVo>> repeatOrder(@RequestBody TShareOrderParam tShareOrderParam) {
        Long uid = LocalUser.getUser().getUid();
        tShareOrderParam.setUserId(uid.intValue());
        log.info("开门、续单的订单接口");
        log.info("tShareOrderParam.getOperFlag():" + tShareOrderParam.getOperFlag());
        List<TShareOrderVo> tShareOrderVoList = tShareOrderService.repeatOrder(tShareOrderParam);
        return ApiResult.ok(tShareOrderVoList);
    }

    /**
     * 根据门店Id、房间Id,获取房间的大门、房间智能开关
     */
    @AppLog(value = "根据门店Id、房间Id,获取房间的大门、房间智能开关", type = 1)
    @AuthCheck
    @PostMapping("/storeRoomDevice")
    @ApiOperation(value = "根据门店Id、房间Id,获取房间的大门、房间智能开关", notes = "根据门店Id、房间Id,获取房间的大门、房间智能开关")
    public ApiResult<List<TShareOrderForSwitchVo>> getStoreRoomDevice(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
/*        Long uid = LocalUser.getUser().getUid();
        tShareOrderParam.setUserId(uid.intValue());*/
        List<TShareOrderForSwitchVo> list = tShareOrderService.getStoreRoomDevice(tShareOrderParam);
        return ApiResult.ok(list);
    }


    /**
     * 订单页面点具体一个订单的续单接口
     * 根据用户id获取当前正在使用的订单
     * 没用到
     */
    @AppLog(value = "订单页面点具体一个订单的续单接口", type = 1)
    @AuthCheck
    @PostMapping("/repeatOrderList")
    @ApiOperation(value = "订单页面点具体一个订单的续单接口", notes = "订单页面点具体一个订单的续单接口")
    public ApiResult<TShareOrderVo> repeatOrderList(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Long uid = LocalUser.getUser().getUid();
        tShareOrderParam.setUserId(uid.intValue());
        TShareOrderVo tShareOrderVo = tShareOrderService.repeatOrderList(tShareOrderParam);
        return ApiResult.ok(tShareOrderVo);
    }

    /**
     * 首页单个订单开门码调用接口
     * 根据用户id获取订单二维码
     */
    @AppLog(value = "首页单个订单开门码调用接口", type = 1)
    //@AuthCheck
    @PostMapping("/getOrderQrCode")
    @ApiOperation(value = "首页单个订单开门码调用接口", notes = "首页单个订单开门码调用接口")
    public ApiResult<List<TShareOrderForSwitchVo>> getOrderQrCode(@Validated @RequestBody TShareOrderParam tShareOrderParam) throws UnsupportedEncodingException {
        List<TShareOrderForSwitchVo> tShareOrderForSwitchVos = tShareOrderService.getOrderQrCode(tShareOrderParam.getUserId());
        return ApiResult.ok(tShareOrderForSwitchVos);
    }


    /**
     * 查询根据用户id获取用户全部状态的订单列表接口
     * 根据用户id查询用户全部状态的订单
     */
    @AppLog(value = "查询根据用户id获取用户全部状态的订单列表接口", type = 1)
    @AuthCheck
    @PostMapping("/getOrderListByUserId")
    @ApiOperation(value = "getOrderListByUserId", notes = "查询根据用户id获取用户全部状态的订单列表接口")
    public ApiResult<List<TShareOrderVo>> getOrderListByUserId(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Long uid = LocalUser.getUser().getUid();
        tShareOrderParam.setUserId(uid.intValue());
        // 查询用户全部订单
        if (tShareOrderParam.getStartFlag() == 0) {
            tShareOrderParam.setOrderStatus(null);
        // 查询用户未支付订单
        } else if (tShareOrderParam.getStartFlag() == 1) {
            tShareOrderParam.setOrderStatus(0);
        // 查询用户使用中的订单
        } else if (tShareOrderParam.getStartFlag() == 2) {
            tShareOrderParam.setOrderStatus(2);
        } else if (tShareOrderParam.getStartFlag() == 3) {
            tShareOrderParam.setOrderStatus(4);
        }
        List<TShareOrderVo> list = tShareOrderService.getOrderListByUserId(tShareOrderParam);
        return ApiResult.ok(list);
    }

    /**
     * 查询已完成订单接口
     * 根据用户id查询完成的订单
     */
    @AppLog(value = "查询已完成订单接口", type = 1)
    @AuthCheck
    @PostMapping("/successOrder")
    @ApiOperation(value = "successOrder", notes = "查询已完成订单接口")
    public ApiResult<List<TShareOrderVo>> successOrder(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Long uid = LocalUser.getUser().getUid();
        //List<TShareOrderVo> list = tShareOrderService.successOrder(tShareOrderParam.getUserId());
        List<TShareOrderVo> list = tShareOrderService.successOrder(uid.intValue());
        return ApiResult.ok(list);
    }

    /**
     * 查询待使用的订单列表接口
     * 根据用户id查询待使用的订单列表
     */
    @AppLog(value = "待使用的订单列表", type = 1)
    @AuthCheck
    @PostMapping("/toUseOrder")
    @ApiOperation(value = "toUseOrder", notes = "待使用的订单列表")
    public ApiResult<List<TShareOrderVo>> toUseOrder(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Long uid = LocalUser.getUser().getUid();
        List<TShareOrderVo> list = tShareOrderService.toUseOrder(uid.intValue());
        return ApiResult.ok(list);
    }

    /**
     * 查询待使用中的订单列表接口
     * 根据用户id查询使用中的订单列表
     */
    @AppLog(value = "使用中的订单列表", type = 1)
    @AuthCheck
    @PostMapping("/inUseOrder")
    @ApiOperation(value = "inUseOrder", notes = "使用中的订单列表")
    public ApiResult<List<TShareOrderVo>> inUseOrder(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Long uid = LocalUser.getUser().getUid();
        List<TShareOrderVo> list = tShareOrderService.inUseOrder(uid.intValue());
        return ApiResult.ok(list);
    }

    /**
     * 查询已取消的订单列表接口
     * 根据用户id查询已取消的订单列表
     */
    @AppLog(value = "已取消的订单列表", type = 1)
    @AuthCheck
    @PostMapping("/cancelOrder")
    @ApiOperation(value = "cancelOrder", notes = "已取消的订单列表")
    public ApiResult<List<TShareOrderVo>> cancelOrder(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Long uid = LocalUser.getUser().getUid();
        List<TShareOrderVo> list = tShareOrderService.cancelOrder(uid.intValue());
        return ApiResult.ok(list);
    }


    /**
     * 查询待付款的订单列表接口
     * 根据用户id查询待付款的订单列表
     */
    @AppLog(value = "待付款的订单列表", type = 1)
    @AuthCheck
    @PostMapping("/toBePaidOrder")
    @ApiOperation(value = "toBePaidOrder", notes = "待付款的订单列表")
    public ApiResult<List<TShareOrderVo>> toBePaidOrder(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Long uid = LocalUser.getUser().getUid();
        List<TShareOrderVo> list = tShareOrderService.toBePaidOrder(uid.intValue());
        return ApiResult.ok(list);
    }


    /**
     * 用户下单支付
     *
     * @return ApiResult<SortedMap < String, String>>   ApiResult<Map<String, Object>>
     */

    @AppLog(value = "用户下单支付", type = 1)
    @AuthCheck
    @NoRepeatSubmit
    @PostMapping("/orderPay")
    @ApiOperation(value = "用户下单支付", notes = "用户下单支付")
    public ApiResult<Map<String, Object>> orderPay(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        log.info("orderPay -> {}", tShareOrderParam.toString());
        YxUser yxUser = LocalUser.getUser();
        tShareOrderParam.setUserPhone(yxUser.getPhone());
        //tShareOrderParam.setOpenId(yxUser.getWxProfile().getRoutineOpenid());
        tShareOrderParam.setAppUserId(yxUser.getWxProfile().getRoutineOpenid());
        Date nowDate = new Date();
        Map<String, String> jsConfig = new HashMap<>();
        WxPayMpOrderResult wxPayMpOrderResult = null;
        //return ApiResult.ok(tShareOrderService.orderPay(tShareOrderParam));
        List<TShareOrder> list = tShareOrderService.createOrder(tShareOrderParam);
        if (list.size() < 1) {
            throw new XunyinException("订单生成失败");
        }
        //查看是否使用优惠券
/*        TMainCouponUser tMainCouponUser = null;
        if (tShareOrderParam.getUseCouponId() != null) {
            tMainCouponUser = tmainCouponUserMapper.selectById(tShareOrderParam.getUseCouponId());
        }*/

        // 如果是余额支付
        if (tShareOrderParam.getPayType() == 0 || tShareOrderParam.getPayType() == 1) {

            for (TShareOrder teaOrder : list) {
                String appOrderNo = teaOrder.getAppOrderNo();
                TShareOrder orderInfo = tShareOrderService.selectByAppOrderNo(appOrderNo);
                tShareOrderService.paySuccess(orderInfo);
            }
            jsConfig.put("payMoney0Success", "1");

        // 微信支付
        } else {

            for (TShareOrder teaOrder : list) {
                String appOrderNo = teaOrder.getAppOrderNo();
                if (teaOrder.getPayMoney().compareTo(new BigDecimal(0)) > 0) {

                    wxPayMpOrderResult = (WxPayMpOrderResult) weixinPayShareBusService
                            .unifyPay(teaOrder.getStoreId(), appOrderNo, AppFromEnum.ROUNTINE.getValue(), BillDetailEnum.TYPE_3.getValue(), "小程序包间预约购买");

                    jsConfig.put("appId", wxPayMpOrderResult.getAppId());
                    jsConfig.put("timeStamp", wxPayMpOrderResult.getTimeStamp());
                    jsConfig.put("paySign", wxPayMpOrderResult.getPaySign());
                    jsConfig.put("nonceStr", wxPayMpOrderResult.getNonceStr());
                    jsConfig.put("package", wxPayMpOrderResult.getPackageValue());
                    jsConfig.put("signType", wxPayMpOrderResult.getSignType());
                    // 测试使用
                    //TShareOrder orderInfo = tShareOrderService.selectByAppOrderNo(appOrderNo);
                    //tShareOrderService.paySuccess(orderInfo);

                } else {

                    TShareOrder orderInfo = tShareOrderService.selectByAppOrderNo(appOrderNo);
                    tShareOrderService.paySuccess(orderInfo);
                    jsConfig.put("payMoney0Success", "1");

                    //更新支付成功结果
/*                    TShareOrder updateTeaOrder = new TShareOrder();
                    updateTeaOrder.setId(teaOrder.getId());
                    updateTeaOrder.setResultFlag(ResultFlag.PAID.getValue());
                    updateTeaOrder.setPayTime(nowDate);
                    updateTeaOrder.setOrderStatus(OrderStatusEnum.PAID.getValue());
                    updateTeaOrder.setUpdateTime(nowDate);
                    tShareOrderMapper.update(updateTeaOrder, Wrappers.<TShareOrder>lambdaQuery()
                            .eq(TShareOrder::getId, teaOrder.getId()));*/
                }
            }
            //1-我的钱包；2-线下现金；3-微信；4-支付宝；5-二维码支付；6-其他
            jsConfig.put("payType", "3");

        }



/*        if(list.size()==1){
            //查看是否使用优惠券-有的话就扣除
            if (tShareOrderParam.getUseCouponId() != null && tMainCouponUser != null) {
                tMainCouponUser.setId(tShareOrderParam.getUseCouponId());
                tMainCouponUser.setUseStatus(CommonConst.ORDER_SERVICE);
                tMainCouponUser.setUseTime(new Date());
                tmainCouponUserMapper.update(tMainCouponUser, Wrappers.<TMainCouponUser>lambdaQuery()
                        .eq(TMainCouponUser::getId, tMainCouponUser.getId()));
            }
        }*/

        Map<String, Object> data = new HashMap();
        Object payment = jsConfig;
        data.put("payment", payment);
        //data.put("orderInfo", orderInfo);
        return ApiResult.ok(data);
        //return CommonUtil.successJson(jsConfig);
        //return ApiResult.ok(jsConfig);

    }

    /**
     * 立即支付接口
     *
     * @return ApiResult<Map < String, Object>>
     */
    @AppLog(value = "立即支付接口", type = 1)
    @AuthCheck
    @PostMapping("/immediatePay")
    @ApiOperation(value = "立即支付接口", notes = "立即支付接口")
    public ApiResult<Map<String, Object>> immediatePay(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        Integer orderId = tShareOrderParam.getOrderId();
        String appOrderNo = OrderNoUtil.getOrderNo("1011", "");//获取订单号
        Date nowDate = new Date();
        Map<String, String> jsConfig = new HashMap<>();
        WxPayMpOrderResult wxPayMpOrderResult = null;
        //查询订单
        TShareOrder teaOrder = tShareOrderMapper.selectById(orderId);
        teaOrder.setAppOrderNo(appOrderNo);
        //更新订单号
        tShareOrderMapper.update(teaOrder, Wrappers.<TShareOrder>lambdaQuery()
                .eq(TShareOrder::getId, teaOrder.getId()));
        if (teaOrder.getPayMoney().compareTo(new BigDecimal(0)) > 0) {
            wxPayMpOrderResult = (WxPayMpOrderResult) weixinPayShareBusService
                    .unifyPay(teaOrder.getStoreId(), appOrderNo, AppFromEnum.ROUNTINE.getValue(), BillDetailEnum.TYPE_3.getValue(), "小程序茶室预约购买");

            jsConfig.put("appId", wxPayMpOrderResult.getAppId());
            jsConfig.put("timeStamp", wxPayMpOrderResult.getTimeStamp());
            jsConfig.put("paySign", wxPayMpOrderResult.getPaySign());
            jsConfig.put("nonceStr", wxPayMpOrderResult.getNonceStr());
            jsConfig.put("package", wxPayMpOrderResult.getPackageValue());
            jsConfig.put("signType", wxPayMpOrderResult.getSignType());

            // 测试使用
            // TShareOrder orderInfo = tShareOrderService.selectByAppOrderNo(appOrderNo);
            // tShareOrderService.paySuccess(orderInfo);

        } else {
            TShareOrder orderInfo = tShareOrderService.selectByAppOrderNo(appOrderNo);
            tShareOrderService.paySuccess(orderInfo);
            jsConfig.put("payMoney0Success", "1");

/*            jsConfig.put("payMoney0Success", "1");
            //更新支付成功结果
            TShareOrder updateTeaOrder = new TShareOrder();
            updateTeaOrder.setId(teaOrder.getId());
            updateTeaOrder.setResultFlag(ResultFlag.PAID.getValue());
            updateTeaOrder.setPayTime(nowDate);
            updateTeaOrder.setOrderStatus(OrderStatusEnum.PAID.getValue());
            updateTeaOrder.setUpdateTime(nowDate);
            tShareOrderMapper.update(updateTeaOrder, Wrappers.<TShareOrder>lambdaQuery()
                    .eq(TShareOrder::getId, teaOrder.getId()));*/


        }
        Map<String, Object> data = new HashMap();
        Object payment = jsConfig;
        data.put("payment", payment);
        return ApiResult.ok(data);
        //return CommonUtil.successJson(jsConfig);
        //return ApiResult.ok(jsConfig);

        //return ApiResult.ok(tShareOrderService.immediatePay(tShareOrderParam));
    }


    /**
     * 充值用户下单支付 @return
     *
     * @return ApiResult<Map < String, Object>>
     */
    @AppLog(value = "充值用户下单支付", type = 1)
    //@AuthCheck
    @PostMapping("/rechargeOrderPay")
    @ApiOperation(value = "充值用户下单支付", notes = "充值用户下单支付")
    public ApiResult<Map<String, String>> rechargeOrderPay(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        //return orderService.rechargeOrderPay(jsonObject);

        TRechargeOrder tRechargeOrder = tShareOrderService.createRechargeOrder(tShareOrderParam);
        log.info("rechargeOrderPay -> {}", tShareOrderParam.toString());
        Map<String, String> jsConfig = new HashMap<>();
        WxPayMpOrderResult wxPayMpOrderResult = (WxPayMpOrderResult) weixinPayShareBusService
                .unifyPay(tRechargeOrder.getTeaHouseId(), tRechargeOrder.getAppOrderNo(), AppFromEnum.ROUNTINE.getValue(), BillDetailEnum.TYPE_1.getValue(), "小程序充值购买");

        jsConfig.put("appId", wxPayMpOrderResult.getAppId());
        jsConfig.put("timeStamp", wxPayMpOrderResult.getTimeStamp());
        jsConfig.put("paySign", wxPayMpOrderResult.getPaySign());
        jsConfig.put("nonceStr", wxPayMpOrderResult.getNonceStr());
        jsConfig.put("package", wxPayMpOrderResult.getPackageValue());
        jsConfig.put("signType", wxPayMpOrderResult.getSignType());
        return ApiResult.ok(jsConfig);

        //return ApiResult.ok(tShareOrderService.rechargeOrderPay(tShareOrderParam));


    }

    /**
     * 用户取消订单-退款接口
     *
     * @return ApiResult
     */
    @AppLog(value = "用户取消订单-退款接口", type = 1)
    @AuthCheck
    @PostMapping("/cancelOrderPay")
    @ApiOperation(value = "用户取消订单-退款接口", notes = "用户取消订单-退款接口")
    public ApiResult<String> cancelOrderPay(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        log.debug("取消订单");
        Integer orderId = tShareOrderParam.getOrderId();
        YxUser yxUser = LocalUser.getUser();
        tShareOrderParam.setUserId(yxUser.getUid().intValue());
        Integer userId = tShareOrderParam.getUserId();
        Date nowDate = new Date();
        TShareOrder teaOrder = tShareOrderMapper.selectById(orderId);
        //判断订单表状态(已付款15分钟前可取消)
        boolean flag = false;
        if (teaOrder.getOrderStatus() == 1) {
            // 当前时间小于预约开始时间
            if (teaOrder.getTeaServerStartTime().getTime() > nowDate.getTime()) {
                long newTime = nowDate.getTime();
                long TeaServerStartTime = teaOrder.getTeaServerStartTime().getTime();
                long out = (TeaServerStartTime - newTime) / 1000;
//                int orderTimeLong = DateUtil.getDateDiffLong(nowDate, teaOrder.getTeaServerStartTime());
//                if (Math.abs(orderTimeLong-0)>1800) {
                if (out > 120) {
                    TShareOrder order = new TShareOrder();
                    //取消订单-有付金额进行退款，没有付金额进行返券
                    if (teaOrder.getPayMoney().compareTo(new BigDecimal(0)) > 0) {
                        //退款
                        //退款后更新订单退款状态
                        //refundOrder(teaOrder);
                        // 如果是余额支付,则退回对应的余额
                        if (teaOrder.getPayType() == 0 || teaOrder.getPayType() == 1) {
                            tShareOrderService.refundProcess(teaOrder);

                        // 如果是微信支付
                        } else {

                            weixinPayService.refundOrder(teaOrder);
                            //tShareOrderService.refundConpon(teaOrder);
                        }
                    } else {

                        tShareOrderService.refundProcess(teaOrder);
/*                        order.setId(teaOrder.getId());
                        order.setServiceStatus(5);
                        order.setOrderStatus(3);
                        order.setUpdateUserId(userId);
                        order.setUpdateTime(nowDate);

                        tShareOrderMapper.update(order, Wrappers.<TShareOrder>lambdaQuery()
                                .eq(TShareOrder::getId, teaOrder.getId()));*/

                        // 如果有使用优惠券,则把抵扣的优惠券还原未使用状态

                        // 如果有使用卡券（小时卡、次数卡）,则还原抵扣（小时卡、次数卡）小时数或次数还原


                    }


                }
                flag = true;
            } else {
                flag = false;
            }

        // 如果是未支付取消订单
        } else if (teaOrder.getOrderStatus() == 0) {

            TShareOrder order = new TShareOrder();
            order.setId(teaOrder.getId());
            order.setServiceStatus(5);
            order.setOrderStatus(OrderStatusEnum.CANCELLED.getIndex());
            order.setUpdateUserId(userId);
            order.setUpdateTime(nowDate);
            tShareOrderMapper.update(order, Wrappers.<TShareOrder>lambdaQuery()
                    .eq(TShareOrder::getId, teaOrder.getId()));
            flag = true;

        }

        if (flag) {
            gzhOrderCancelSuccessNotice(orderId);
            return ApiResult.ok("取消成功");
        } else {
            return ApiResult.ok("订单距离服务15分钟内不可取消");
            // return ApiResult.fail(ErrorEnum.E_100013.getErrorMsg());
        }
/*        Boolean flag = tShareOrderService.cancelOrderPay(tShareOrderParam);


       if (flag) {
            return ApiResult.ok("取消成功");
        } else {
            return ApiResult.fail(ErrorEnum.E_100013.getErrorMsg());
        }*/
    }

    /**
     * 公众号消息-公众号消息取消订单通知门店保洁员
     * @param orderId
     */
    private void gzhOrderCancelSuccessNotice(Integer orderId){
        TShareOrder teaOrder = tShareOrderMapper.selectById(orderId);
        // 模板消息取消订单发布事件
        TemplateBean templateBean = TemplateBean.builder()
                .storeId(teaOrder.getStoreId())
/*                .storeName(teaOrder.getStoreName())
                .orderNo(teaOrder.getOrderNo())
                .orderMondey(teaOrder.getOrderMondey())*/
                .userPhone(teaOrder.getUserPhone())
                .storeRoomName(teaOrder.getStoreRoomName())
                .updateTime(teaOrder.getUpdateTime())
                .teaServerStartTime(teaOrder.getTeaServerStartTime())
                .teaServerEndTime(teaOrder.getTeaServerEndTime())
                .templateType(TemplateListenEnum.TYPE_15.getValue())
                .build();

        publisher.publishEvent(new TemplateEvent(this, templateBean));

    }

    /**
     * 保洁员设置已完成的订单为清洁状态
     *
     * @return ApiResult
     */
    @AppLog(value = "保洁员设置已完成的订单为清洁状态", type = 1)
    //@AuthCheck
    @PostMapping("/insertIntoRecord")
    @ApiOperation(value = "保洁员设置已完成的订单为清洁状态接口", notes = "保洁员设置已完成的订单为清洁状态接口")
    public ApiResult<Boolean> insertIntoRecord(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        tShareOrderService.insertIntoRecord(tShareOrderParam);
//        // 断电
//        TDevice device = tDeviceService.getPowerDeviceByStoreRoomIdOrStoreId(tShareOrderParam.getStoreId(), tShareOrderParam.getStoreRoomId(), 4);
//        if (device != null) {
//            DeviceParam param1 = new DeviceParam();
//            param1.setType(1);
//            param1.setCommandType(1);
//            param1.setMacAddr(device.getMacAddr());
//            param1.setSubPortStr("0,0,0,0");
//            sendCommondProg(param1);
//            param1 = new DeviceParam();
//            param1.setCommandType(3);
//            param1.setMacAddr(device.getMacAddr());
//            param1.setVoiceText("电源已关，请收拾好贵重物品离开，欢迎下次光临");
//            sendCommondProg(param1);
//        }
        // 断电
        TDevice device = tDeviceService.getPowerDeviceByStoreRoomIdOrStoreId(tShareOrderParam.getStoreId(), tShareOrderParam.getStoreRoomId(), 2);
        if (device != null) {
            DeviceUtil1.adminLock(device.getDeviceNo());
        }
        return ApiResult.ok();
    }

    private void sendCommondProg(DeviceParam param) {
        if(param.getType()==null){
            param.setType(0);
        }
        List relayList = new ArrayList<>();
        if(param.getType()==1){
            log.info("param.getSubPortStr():"+param.getSubPortStr());
            relayList.add(0);
            relayList.add(0);
            relayList.add(0);
            relayList.add(0);
            String[] subPortArr = param.getSubPortStr().split(",");
            for(int i =0;i<subPortArr.length;i++){
                log.info("subPortArr_"+i+":"+subPortArr[i]);
                relayList.set(i,subPortArr[i]);
            }
            log.info("relayList.toString()"+relayList.toString());
            for(int j=0;j<relayList.size();j++){
                log.info("relayList.get(j)_"+j+":"+relayList.get(j));
            }
        }
        try {
            PubMsg.sendCommand(param.getMacAddr(), param.getCommandType(), param.getSwitchFlag(), param.getVoiceText(),param.getType(),relayList,"");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保洁人员订单管理接口
     *
     * @return ApiResult
     */
    @AppLog(value = "保洁人员订单管理接口", type = 1)
    //@AuthCheck
    @PostMapping("/loadTeaHouseOrder4Manage")
    @ApiOperation(value = "保洁人员订单管理接口", notes = "保洁人员订单管理接口")
    public ApiResult<List<TShareOrderVo>> loadTeaHouseOrder4Manage(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        if (tShareOrderParam.getOrderStatus() == 0) {
            tShareOrderParam.setOrderStatus(null);
        }
        return ApiResult.ok(tShareOrderService.loadTeaHouseOrder4Manage(tShareOrderParam.getStoreId(), tShareOrderParam.getOrderStatus(),tShareOrderParam.getDayNum()));
    }

    /**
     * 管理人员查询预约订单关联保洁记录管理接口
     *
     * @return ApiResult
     */
    @AppLog(value = "管理人员查询预约订单关联保洁记录管理接口", type = 1)
    //@AuthCheck
    @PostMapping("/loadTeaHouseOrder4ManageByClean")
    @ApiOperation(value = "管理人员查询预约订单关联保洁记录管理接口", notes = "管理人员查询预约订单关联保洁记录管理接口")
    public ApiResult<List<TShareOrderVo>> loadTeaHouseOrder4ManageByClean(@Validated @RequestBody TShareOrderParam tShareOrderParam) {
        if (tShareOrderParam.getOrderStatus() == 0) {
            tShareOrderParam.setOrderStatus(null);
        }
        return ApiResult.ok(tShareOrderService.loadTeaHouseOrder4ManageByCleaningRecord(tShareOrderParam.getStoreId(), tShareOrderParam.getOrderStatus(),tShareOrderParam.getDayNum()));
    }

    /**
     * 图片上传
     *
     * @param imagefile 图片
     * @return
     * @throws Exception
     */
    @AppLog(value = "图片上传", type = 1)
    //@AuthCheck
    @PostMapping("/uploadImage")
    @ApiOperation(value = "图片上传", notes = "图片上传")
    public JSONObject uploadImage(@RequestParam(value = "imagefile", required = false) MultipartFile imagefile)
            throws Exception {
        return fileService.uploadSingle(imagefile, "backstage");
    }

    @AppLog(value = "根据门店id获取房间列表", type = 1)
    @ApiOperation("根据门店id获取房间列表")
    @PostMapping("/listRoomByStoreId")
    public ApiResult<List<MtStoreRoom>> listRoomByStoreId(@Validated @RequestBody TStoreRoomQueryParam queryParam) {
        List<MtStoreRoom> list = mtStoreRoomService.listRoom(queryParam);
        if (list != null) {
            list = list.stream().filter(mtStoreRoom -> Integer.valueOf(0).equals(mtStoreRoom.getIsDel())
                    && Integer.valueOf(1).equals(mtStoreRoom.getStatus())
                    && Integer.valueOf(0).equals(mtStoreRoom.getStoreRoomStatus())
                    && "A".equals(mtStoreRoom.getRoomOnlineStatus())).collect(Collectors.toList());
        }
        return ApiResult.ok(list);
    }

    @AppLog(value = "换包厢", type = 1)
    //@AuthCheck
    @PostMapping("/exchangeRoom")
    @ApiOperation(value = "换包厢接口", notes = "换包厢接口")
    public ApiResult<String> exchangeRoom(@Validated @RequestBody ExchangeRoomParam exchangeRoomParam) {
        TShareOrder tShareOrder = tShareOrderService.getById(exchangeRoomParam.getOrderId());
        if (tShareOrder == null) {
            return ApiResult.fail("订单不存在");
        }
        if (tShareOrder.getStoreRoomId().equals(exchangeRoomParam.getStoreRoomId())) {
            return ApiResult.ok("操作成功");
        }
        if (tShareOrder.getOrderStatus().intValue() != 1 && tShareOrder.getOrderStatus().intValue() != 2) {
            return ApiResult.fail("订单状态不在已支付或者服务中");
        }
        if ((tShareOrder.getTeaServerStartTime().getTime() + 600000L) < (System.currentTimeMillis())) {
            return ApiResult.fail("订单已进行10分钟了，不允许更换");
        }
        // 判断新房间
        MtStoreRoom mtStoreRoom = mtStoreRoomService.getById(exchangeRoomParam.getStoreRoomId());
        if (mtStoreRoom == null
                || !Integer.valueOf(0).equals(mtStoreRoom.getIsDel())
                || !tShareOrder.getStoreId().equals(mtStoreRoom.getStoreId())
                || !Integer.valueOf(1).equals(mtStoreRoom.getStatus())
                || !"A".equals(mtStoreRoom.getRoomOnlineStatus()) ) {
            return ApiResult.fail("房间不存在");
        }
        if (!Integer.valueOf(0).equals(mtStoreRoom.getStoreRoomStatus())) {
            return ApiResult.fail("房间不在空闲状态");
        }
        MtStoreRoom oldStoreRoom = mtStoreRoomService.getById(tShareOrder.getStoreRoomId());

        mtStoreRoom.setStoreRoomStatus(oldStoreRoom.getStoreRoomStatus());
        mtStoreRoomService.updateById(mtStoreRoom);

        oldStoreRoom.setStoreRoomStatus(0);
        mtStoreRoomService.updateById(oldStoreRoom);
//        // 老房间断电
//        TDevice device = tDeviceService.getPowerDeviceByStoreRoomIdOrStoreId(tShareOrder.getStoreId(), tShareOrder.getStoreRoomId(), 4);
//        if (device != null) {
//            DeviceParam param1 = new DeviceParam();
//            param1.setType(1);
//            param1.setCommandType(1);
//            param1.setMacAddr(device.getMacAddr());
//            param1.setSubPortStr("0,0,0,0");
//            sendCommondProg(param1);
//            param1 = new DeviceParam();
//            param1.setCommandType(3);
//            param1.setMacAddr(device.getMacAddr());
//            param1.setVoiceText("电源已关，请收拾好贵重物品离开，欢迎下次光临");
//            sendCommondProg(param1);
//        }
        // 老房间断电
        TDevice device = tDeviceService.getPowerDeviceByStoreRoomIdOrStoreId(tShareOrder.getStoreId(), tShareOrder.getStoreRoomId(), 2);
        if (device != null) {
            DeviceUtil1.adminLock(device.getDeviceNo());
        }
        tShareOrder.setStoreRoomId(exchangeRoomParam.getStoreRoomId());
        tShareOrder.setStoreRoomName(mtStoreRoom.getStoreRoomName());
        tShareOrderService.updateById(tShareOrder);
        return ApiResult.ok("操作成功");
    }

    @AppLog(value = "终止订单", type = 1)
    //@AuthCheck
    @PostMapping("/finishOrder")
    @ApiOperation(value = "终止订单接口", notes = "终止订单接口")
    public ApiResult<String> finishOrder(@Validated @RequestBody FinishOrderParam finishOrderParam) {
        TShareOrder tShareOrder = tShareOrderService.getById(finishOrderParam.getOrderId());
        if (tShareOrder == null) {
            return ApiResult.fail("订单不存在");
        }
        if (tShareOrder.getOrderStatus().intValue() != 2) {
            return ApiResult.fail("订单状态不在服务中");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        tShareOrder.setTeaServerEndTime(calendar.getTime());
        String endTimeStr = DateUtils.parseDate2String(tShareOrder.getTeaServerEndTime(), "yyyy-MM-dd HH:mm");
        String[] teaServerTimeArr = tShareOrder.getTeaServerTime().split("~");
        String startTimeStr = teaServerTimeArr[0];
        tShareOrder.setTeaServerTime(startTimeStr + "~" + endTimeStr);
        // {"date":"07-20","selectBeginTime":"16:57","endDate":"07-20","selectEndTime":"18:57","sweep":1}
        JSONObject json = JSONObject.parseObject(tShareOrder.getTeaSubscribeTimes());
        json.put("selectEndTime", endTimeStr.substring(11));
        tShareOrder.setTeaSubscribeTimes(json.toJSONString());
        tShareOrderService.updateById(tShareOrder);
        return ApiResult.ok("操作成功");
    }


    /**
     * 包间订单详情
     */
/*    @AppLog(value = "查看包间订单详情", type = 1)
    @AuthCheck
    @GetMapping("/tShareOrder/detail/{key}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "唯一的key", paramType = "query", dataType = "string")
    })
    @ApiOperation(value = "包间订单详情", notes = "包间订单详情")
    public ApiResult<YxStoreOrderQueryVo> detail(@PathVariable String key) {
        Long uid = LocalUser.getUser().getUid();
        if (StrUtil.isEmpty(key)) {
            throw new YshopException("参数错误");
        }
        YxStoreOrderQueryVo storeOrder = storeOrderService.getOrderInfo(key, uid);
        if (ObjectUtil.isNull(storeOrder)) {
            throw new YshopException("订单不存在");
        }
        storeOrder = creatShareProductService.handleQrcode(storeOrder, path);

        return ApiResult.ok(storeOrderService.handleOrder(storeOrder));
    }*/

}
